<template>
  <!--出入管理-->
  <div class="flex flex-column" style="height: 100%">
    <div v-show="formAge" class="home-table-area bg-white flex-sub" style="padding-top:15px;margin-top:0px;">
        <el-tabs v-model="activeName" >
          <el-tab-pane label="发布公告" name="first">
            <el-row class="hr"></el-row>
            <el-row class="home-table">
              <el-col :span="20">
                <el-input class="hta-input" placeholder="搜索关键字" v-model="searchObj.keywords">
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
                <el-button type="primary" @click="getUserList">搜索</el-button>
              </el-col>
              <el-col :span="4">
                <el-button type="primary" @click="formAgetab"><span style="margin:0 30px;">发布公告</span></el-button>
              </el-col>
            </el-row>
            <el-table class="home-table" :data="tableData" :header-cell-style="{background:'#F7F7F7',color:'#101010', fontWeight: 'normal'}">
              <el-table-column prop="title"  label="标题" header-align="center" align="center"></el-table-column>
              <el-table-column show-overflow-tooltip width="600" label="历史发布" header-align="center" align="center">
                <template slot-scope="scope">
                  <span v-html="scope.row.content" style="width:600px;display:block;word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"></span>
                </template>
              </el-table-column>
              <el-table-column label="时间" header-align="center" align="center" width="170">
                <template slot-scope="scope">
                  {{ dateFormat(scope.row.created_at) }}
                </template>
              </el-table-column>
              <el-table-column header-align="center" align="center" label="操作">
                <template slot-scope="scope">
                  <el-button type='text' @click="editInfofirst(scope.row)">详情</el-button>
                  <!-- <el-button type='text' @click="delInfofirst(scope.row)">删除</el-button> -->
                </template>
              </el-table-column>
            </el-table>
            <el-pagination 
              class="hm-page"
              background
              :page-size="searchObj.page_num"
              layout="prev, pager, next"
              :total="total" @current-change="sizeChange">
            </el-pagination>
          </el-tab-pane>  
          <el-tab-pane label="消息管理" name="second">
            <el-row class="hr"></el-row>
            <el-row class="home-table">
              <el-col :span="18">
                <el-input class="hta-input" placeholder="搜索姓名等关键字" v-model="searchObjs.keywords">
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
                <el-button type="primary" @click="getUserLists">搜索</el-button>
              </el-col>
            </el-row>
            <el-table class="home-table" :data="tableDatas" :header-cell-style="{background:'#F7F7F7',color:'#101010', fontWeight: 'normal'}">
              <el-table-column prop="message_title" label="标题" header-align="center" align="center"></el-table-column>
              <el-table-column prop="message_content" show-overflow-tooltip width="700" label="内容" header-align="center" align="center"></el-table-column>
              <el-table-column label="消息类型" header-align="center" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.message_type === 'SYSTEM'">系统通知</span>
                  <span v-if="scope.row.message_type === 'ORDER'">订单通知</span>
                </template>
              </el-table-column>
              <el-table-column label="时间" header-align="center" align="center" width="170">
                <template slot-scope="scope">
                  {{ dateFormat(scope.row.created_at) }}
                </template>
              </el-table-column>
              <el-table-column header-align="center" align="center" label="操作">
                <template slot-scope="scope">
                  <el-button type='text' @click="editInfo(scope.row)">详情</el-button>
                  <el-button type='text' @click="delInfo(scope.row.message_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              class="hm-page"
              background
              layout="prev, pager, next"
              :total="total" @current-change="sizeChange">
            </el-pagination>
          </el-tab-pane>
          <!-- <el-tab-pane label="账户信息" name="third">
            <el-row class="hr"></el-row>
            <el-row class="home-table-area" style="margin-left:100px;">
              <el-col :span="8">
                <img :src='imgimg' class="imgUrl" width="150" height="150"/>
                <el-upload action="#" list-type="picture-card" 
                    :file-list="fileList" :on-change="handleChange" :auto-upload="false">
                    <i slot="default" class="el-icon-plus"></i>
                </el-upload> 
              </el-col>
              <el-col :span="8">
                 <input type="file" accept="image/*" @change="handleFile"   class="hiddenInput" style="display:none;"/>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-button class="float-right" size="mini" @click="uploadHeadImg"><span style="margin:0 10px;">修改</span></el-button>
              </el-col>
            </el-row>
            <el-row style="margin-top:50px;">
              <el-col :span="2" style="margin:5px 10px; 0 0;">
                <span class="float-right">昵称:</span>
              </el-col>
              <el-col :span="5">
                <el-input v-model="name"></el-input>
              </el-col>
            </el-row>
             <el-row style="margin:50px 0;">
              <el-col :span="2" style="margin:5px 10px; 0 0;">
                <span class="float-right">账户:</span>
              </el-col>
              <el-col :span="5">
                <el-input v-model="username"></el-input>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5">
                <span class="float-right">注册时间:{{!!registration_time?registration_time:''}}</span>
              </el-col>
            </el-row>
          </el-tab-pane> -->
        </el-tabs>  
    </div>
    <transition name="fade" >
      <div v-show="formAges" >
        <div class="hm-select-area bg-white font-14"  style="letter-spacing:1px;height:100%;">
          <el-row class="bord">
            <el-col :span="1">
              <i class="el-icon-back" @click="back"></i>
            </el-col>
            <el-col :span="6">
              <div class="yjxq">发布公告</div>
            </el-col>
          </el-row>
            <el-row  class="margin-bottom">
              <el-col :span="4">
                <div class="float-right icons">标题</div>
              </el-col>
              <el-col :span="10">
                  <el-input v-model="addList.title" placeholder="请输入标题"></el-input>
              </el-col>
            </el-row>
            <el-row class="margin-bottom">
             <el-col :span="4" >
                <div class="float-right icons">内容</div>
              </el-col>
              <el-col :span="20">
                <el-upload
                style="display:none"
                :show-upload-list="false"
                :on-success="handleSuccess"
                name="upload_file"
                :format="['jpg','jpeg','png','gif']"
                :max-size="2048"
                multiple
                :file-list="filess"
                action="http://192.168.3.37:8200/admin/system/uploadImage">
                  <el-button icon="ios-cloud-upload-outline" class="elbutton" style="display:none"></el-button>
                </el-upload>
                <quill-editor ref="QuillEditor" v-model="addList.content" :options="editorOption" class="myQuillEditor" />
              </el-col>  
            </el-row>
             <el-row class="margin-bottom">
              <el-col :span="4">
                <span class="float-right icons">封面图</span>
              </el-col>
              <el-col :span="16">
                  <el-upload
                    class="upload-demo"
                    action="#"
                    :on-remove="handleRemove"
                    :on-change="handleChangeUrl"
                    :file-list="fileList"
                    :multiple="false"
                    :limit="1"
                    :auto-upload="false"
                    :on-exceed="handleExceed"
                    list-type="picture">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                  </el-upload>
              </el-col>
            </el-row>
            <div style="text-align:center;margin-top:30px;">
              <el-button type="primary" @click="fbress"><span style="margin:0 40px;">发布</span></el-button>
            </div>
        </div>  
      </div>
    </transition>
    <transition name="fade">
        <div v-show="formAgexqing" >
        <div class="hm-select-area bg-white font-14"  style="letter-spacing:1px;height:100%;">
          <el-row class="bord">
            <el-col :span="1">
              <i class="el-icon-back" @click="backxq"></i>
            </el-col>
            <el-col :span="6">
              <div class="yjxq">公告详情</div>
            </el-col>
            <!-- <el-col :span="22">
              <el-button class="float-right delress" @click="delInfofirst">删除</el-button>
            </el-col> -->
          </el-row>
            <p class="firsttitle">{{!!detailList.title?detailList.title:''}}</p>
            <div class="secondcontant" style="text-indent:2em;" v-html="detailList.content"></div>
        </div>  
      </div>  
    </transition>
    
  </div>
</template>
<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
 // 工具栏配置
    const toolbarOptions = [
      ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
      ['blockquote', 'code-block'],
    
      [{'header': 1}, {'header': 2}],               // custom button values
      [{'list': 'ordered'}, {'list': 'bullet'}],
      [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
      [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
      [{'direction': 'rtl'}],                         // text direction
    
      [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
      [{'header': [1, 2, 3, 4, 5, 6, false]}],
    
      [{'color': []}, {'background': []}],          // dropdown with defaults from theme
      [{'font': []}],
      [{'align': []}],
      ['link', 'image', 'video'],
      ['clean']                                         // remove formatting button
    ]
export default {
  name: 'index',
  components: {
    quillEditor
  },
  data () {
    return {
      imgimg: require('@/assets/images/login_bg.png'),
      addList:{
        title:'',
        content:'',
        img_url:''
      },
      filess:[],
      editorOption: {                
        modules: {
          toolbar: {
            container: toolbarOptions,  // 工具栏
            handlers: {
              'image': function (value) {
                console.log(value)
                if (value) {
                  // console.log(value)
                    document.querySelector('.elbutton').click()
                } else {
                    this.quill.format('image', false);
                }
              }
            }
          }
        }
      },
      name:'',
      username:'',
      registration_time:'2020.02.01',
      activeName:'first',
      formAge:true,
      formAges:false,
      formAgexqing:false,
      detailList:{},
      fileList:[],
      searchObj: {
        keywords: '',
        page: 1,
        page_num: 10,
      },
      searchObjs: {
        keywords: '',
        page: 1,
        page_num: 10,
      },
      total: 10,
      totals:10,
      tableData: [],
      tableDatas: [],
      admin_id:''
    }
  },
  mounted () {
    this.admin_id = this.$store.state.adminId
    this.getOutData()
    this.getOutDatas()
  },
  methods: {
    handleSuccess (res) {
      console.log(res.data.url)
      // 获取富文本组件实例
      let quill = this.$refs.QuillEditor.quill
      // 如果上传成功
      if (res) {
          // 获取光标所在位置
          let length = quill.getSelection().index;
          // 插入图片，res为服务器返回的图片链接地址
          quill.insertEmbed(length, 'image', "http://192.168.3.37:9022"+res.data.url.split("/usr/share/nginx/html/upload")[1])
          // 调整光标到最后
          quill.setSelection(length + 1)
      } else {
          // 提示信息，需引入Message
          Message.error('图片插入失败')
      }
    },
    // 发布
    fbress(){
      if (!this.addList.title) {
        this.$message.error('请输入标题')
        return false
      }
      if (!this.addList.content) {
        this.$message.error('请输入内容')
        return false
      }
      if (this.fileList.length<1) {
        this.$message.error('请添加图片')
        return false
      }
      let formd = new FormData()
      console.log(this.fileList)
      formd.append('upload_file', this.fileList[0].raw)
      this.$api.uploadImage(formd).then(res=>{
        this.addList.img_url = res.url
        this.admin_id = this.admin_id
        this.$api.announce(this.addList).then(res => {
          this.$message({
            type: 'success',
            message: '添加成功'
          })
          this.addList = {
            title:'',
            content:''
          }
          this.fileList = []
          this.formAges = false
          this.formAge = true 
          this.getOutData()
        })
      })  

     
    
     
    },
    // 封面图
    handleChangeUrl(file,fileList){
      this.fileList = fileList
    },
    uploadHeadImg(){
       this.$el.querySelector('.hiddenInput').click()
    },
    handleFile(e){
      let $target = e.target || e.srcElement
      let file = $target.files[0]
      var reader = new FileReader()
      reader.onload = (data) => {
        let res = data.target || data.srcElement
        this.imgimg = res.result
        console.log(this.imgimg)
      }
      reader.readAsDataURL(file)
    },
    // 删除图片
    handleRemove(file,fileList){
      this.fileList = fileList
    },
    handleExceed(){
       this.$message.warning("当前限制选择 1 个文件");
    },
    // 发布公告-详情
    editInfofirst(item){
      this.detailList = item
      this.formAge = false
      this.formAgexqing = true
    },
    //发布公告-发布公告
    formAgetab(){
       this.formAge = false
       this.formAges = true
    },
    // 返回-消息管理
    back(){
      this.formAges = false
      this.formAge = true
    },
    // 返回-发布公告
    backxq(){
      this.formAgexqing = false
      this.formAge = true
    },
    editInfo(){

    },
    // 删除-消息管理
    delInfo(message_id){
      console.log(message_id)
      this.$confirm('此操作将删除该消息,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.deleteMessage({admin_id:this.admin_id,message_id:message_id}).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getUserLists()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });  
    },
    handleChange(val){
      console.log(val)
    },

    // 时间
    dateFormat (date, fmt = 'yyyy-MM-dd hh:mm:ss') {
      date = new Date(date * 1000)
      const o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) }
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
        }
      }
      return fmt
    },
    getUserList () {
      this.searchObj.page = 1
      this.getOutData()
    },
    getUserLists(){
      this.searchObj.page = 1
      this.getOutDatas()
    },
    // 发布公告列表
    getOutData () {
      this.searchObj.admin_id = this.$store.state.adminId
      this.$api.announceList(this.searchObj).then(res => {
        this.tableData = res.list
        this.total = res.total_count
      })
    },
    // 消息列表
    getOutDatas() {
      this.searchObjs.admin_id = this.$store.state.adminId
      this.$api.messageList(this.searchObjs).then(res => {
        this.tableDatas = res.list
        this.totals = res.total_count
      })
    },
    // 临时访客进出记录列表
    sizeChange (val) {
      this.searchObj.page = val
      this.getOutData()
    }

  }
}
</script>

<style scoped>
  .firsttitle{
    text-align:center;
    margin:50px 5%;
    font-size:19px;
    font-weight:600;
    width:90%;
  }
  .secondcontant{
    margin:0 2%;
    width:96%;
  }
  .delress{
   color:#f56c6c;
   border:0px;
   margin-top:-25px;
  }
  .margin-bottom{
    margin-bottom:50px;
  }
  .icons{
    margin:7px 25px 0 10px;
  }
  .el-icon-back{
    font-weight: 500;
    font-size: 25px;
  }
  .bord{
    margin-bottom: 30px;
    font-size: 15px;
    letter-spacing:1px;
  }
  .yjxq{
    font-weight: 500;
    font-size: 18px;
  }
  .amap-demo {
    height: 300px;
  }
  .imgUrl{
    border-radius:50%;
  }
  .home-table-area >>>.el-tabs__nav-wrap::after{
    width: 0%!important;
  }
  .home-table-area >>>.el-tabs__item.is-top{
    font-size:15px;
    letter-spacing: 1px;
  }
  .home-table-area >>>.el-tabs__item.is-top.is-active{
      font-size:17px;
      letter-spacing: 1px;
      
  }
  .hta-input {
    width: 260px;
    margin-right: 23px;
  }
  el-tabs{
    margin-top:30px;
  }
  .hr{
    height:20px;
    width:15550px;
    background-color:#F0F0F0;
  }
</style>
